<template>
  <el-button
      size="mini"
      type="warning"
      icon="el-icon-search"
      @click="getRightList()">分配权限</el-button>


  <el-dialog
      title="权限分配"
      v-model="showSetRightDialog"
      width="70%"
      center>
    <!--    <span>需要注意的是内容是默认不居中的</span>-->
    <!--             @node-click="handleNodeClick"-->

    <el-tree :data="treeData"
             :props="treeProps"
             show-checkbox
             default-expand-all
             :default-checked-keys="defKey"
             node-key="id"
             ref="treeRef"
    ></el-tree>
    <template #footer>
    <span class="dialog-footer">
      <el-button @click="showSetRightDialog = false">取 消</el-button>
      <el-button type="primary" @click="submitRights()">确 定</el-button>
    </span>
    </template>
  </el-dialog>
</template>

<script>
import axios from "axios";

export default {
  name: "RoleSetBtn",
  props: ['id', 'row'],
  emits:['update'],
  data() {
    return {
      showSetRightDialog: false,
      treeData: [],
      defKey: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      roleId:''
    }
  },
  methods: {

    //通过递归的形式获取三级权限 node id 报错到defKey
    getDefKey(node, arr) {
      // console.log(node)
      if (undefined === node.children) {
        arr.push(node.id)
      } else {
        node.children.forEach(item => {
          this.getDefKey(item, arr)
        })
      }

    },
    async getRightList() {
      this.$message.info("请求ing")
      this.getDefKey(this.row, this.defKey)
      const {data: res} = await axios.get('rights/tree')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error("请求失败")
      }
      this.treeData = res.data
      console.log(this.treeData)
      this.showSetRightDialog = true
    },
    //获取tree view roleId
    async submitRights() {
      const rs = [
          //展开运算符
          ...this.$refs.treeRef.getHalfCheckedKeys(),
          ...this.$refs.treeRef.getCheckedKeys(),
      ]

    const rightStr= rs.join(',')

      const {data:res} = await axios
          .post(`roles/${this.id}/rights`,{
            rids:rightStr
          })

      if (res.meta.status !== 200) {
        return this.this.$message.error("请求失败")
      }
      this.$message.success("请求成功")
      this.$emit("update")
      this.showSetRightDialog = false
      this.defKey = []
      // console.log(rsStr)
    },
  },
}
</script>

<style scoped>

</style>